/**
  * 2023年618活动相关数据的store
  * @author: Ruan Jiazhen
  * @date: 2024-04-29 10:24:56
* */

import dayjs from 'dayjs';
import { defineStore } from 'pinia';
import { reqGet618GiftList, reqGetGiftExchangeBroadcastList, reqGetRedeemRecord, reqRedeem618Gift } from '@/api/api-618';
import { reqGetActivityRule } from '@/api/api-activity';
import { addClassToHtml, randomId } from '@/utils/tools';

export const useActivity618 = defineStore('activity618', () => {
  // #region  礼品相关
  /** 618活动礼品列表 */
  const giftList = ref<GiftItemInfo[]>([]);

  /** 获取618活动礼品列表 */
  const getGiftList = async () => {
    const res = await reqGet618GiftList();
    giftList.value = res?.data?.data.list.map((item: any) => ({
      id: item.exchange_id,
      img: item.icon,
      name: item.title,
      exchangedNum: item.exchange_size,
      stockNum: item.remain_size,
      price: item.miao_dou,
      originalPrice: item.price,
      detailImg: item.detailImg,
      successDesc: item.sendInfo,
      isExchanged: item.isExchanged === '1',
      courseId: item.target_id,
    }));
    console.log('giftList', giftList.value);
  };

  /** 兑换礼品记录 */
  const redeemRecord = ref<RedeemRecord[]>([]);

  /** 获取兑换礼品记录 */
  const getRedeemRecord = async () => {
    const res = await reqGetRedeemRecord();
    redeemRecord.value = res?.data?.data.list.map((item: any) => ({
      id: item.exchange_id,
      time: dayjs(item.create_time).format('YYYY-MM-DD HH:mm:ss'),
      content: item.title,
      desc: item.sendInfo,
      courseId: item.target_id,
    }));
    console.log('redeemRecord', redeemRecord.value);
  };

  /**
   * 兑换618活动礼品
   * @param giftId 礼品id
   */
  const redeemGift = async (giftId: string) => {
    const res = await reqRedeem618Gift(giftId);
    return res?.data?.data.code;
  };

  // #endregion

  // #region 礼品兑换广播相关

  /** 礼品兑换广播列表 */
  const giftExchangeBroadcastList = ref<BroadcastInfo[]>([]);

  /** 获取礼品兑换广播列表 */
  const getGiftExchangeBroadcastList = async () => {
    const res = await reqGetGiftExchangeBroadcastList() as any;
    console.log('getGiftExchangeBroadcastList', res);
    giftExchangeBroadcastList.value = res?.data?.data.list.map((item: any) => ({
      id: randomId(),
      avatar: item.avator,
      nickname: item.emcee_name,
      content: `获得了${item.title}`,
    }));
    console.log('giftExchangeBroadcastList', giftExchangeBroadcastList.value);
  };

  // #endregion

  // #region 规则相关

  /** 618活动规则（富文本） */
  const rule = ref('');

  /** 获取618活动规则（富文本） */
  const getRule = async () => {
    const res = await reqGetActivityRule('activity618');
    const ruleText = res?.data?.data.ruleValue as string;
    rule.value = addClassToHtml(ruleText);
  };

  // #endregion

  return {
    giftList,
    getGiftList,
    redeemRecord,
    getRedeemRecord,
    redeemGift,

    giftExchangeBroadcastList,
    getGiftExchangeBroadcastList,

    rule,
    getRule,
  };
});
